<template>
  <!-- 底部bar -->
  <div class="footer_bar">
    <van-tabbar
      v-model="active"
      active-color="#32b088"
      inactive-color="#cacdd5"
      router
    >
      <van-tabbar-item
        v-for="(item, index) in tabs"
        :key="index"
        :class="['iconfont', item.icon, { selected: active === index }]"
        :to="item.to"
      >
        {{ item.label }}
      </van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
// 数据
import { ref, watch } from "vue";
import { useRoute } from "vue-router";
// 路由对象
const route = useRoute();

// tab 配置数据
const active = ref(0);
const tabs = [
  { label: "Service", icon: "icon-home", to: "/Service" },
  { label: "Pet Care", icon: "icon-icon_tabbar_petcare", to: "/PetCare" },
  { label: "My pet", icon: "icon-icon_tabbar_mypet", to: "/MyPet" },
];
// 更智能的路由匹配
const setActiveByRoute = () => {
  // 获取基础路径（去掉参数）
  const basePath = route.path.split("/").slice(0, 2).join("/") || "/";

  const index = tabs.findIndex(
    (tab) =>
      tab.to === basePath ||
      tab.to === route.path ||
      route.path.startsWith(tab.to)
  );

  active.value = index !== -1 ? index : 0;
};
setActiveByRoute();

// 路由变化监听
watch(route, () => {
  setActiveByRoute();
});
</script>

<style lang="scss">
.van-tabbar {
  height: 70px;
  .van-tabbar-item {
    font-weight: bold;
    font-size: 14px;
  }

  .iconfont {
    &::before {
      width: 40px;
      height: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 14px;
      background-color: #f3f5f7; /* 默认背景色 */
      font-size: 20px;
    }

    /* 选中时的样式 */
    &.selected::before {
      background-color: #c8f5eb; /* 选中背景色 */
    }
  }
}
</style>
